package lh.companion.track.server.netty;

import com.alibaba.fastjson.JSON;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import lh.companion.track.server.model.RealTrack;

import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.Random;

/**
 * Created by lh on 2017/12/20.
 */
public class NettyClient {

    /**
     * @param MinLon：最新经度 MaxLon： 最大经度   MinLat：最新纬度   MaxLat：最大纬度    type：设置返回经度还是纬度
     * @return
     * @throws
     * @Title: randomLonLat
     * @Description: 在矩形内随机生成经纬度
     */
    public double randomLonLat(double MinLon, double MaxLon, double MinLat, double MaxLat, String type) {
        BigDecimal db = new BigDecimal(Math.random() * (MaxLon - MinLon) + MinLon);
        double lon = db.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();// 小数后6位
        db = new BigDecimal(Math.random() * (MaxLat - MinLat) + MinLat);
        double lat = db.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (type.equals("Lon")) {
            return lon;
        } else {
            return lat;
        }
    }

    public static void main(String[] arg) throws URISyntaxException {
        IO.Options options = new IO.Options();
//        options.reconnectionAttempts = 2;
//        options.reconnectionDelay = 1000;//失败重连的时间间隔
//        options.timeout = 500;//连接超时时间(ms)
//        options.path = "/activity";

        NettyClient client = new NettyClient();
        client.createSocket("http://localhost:9084/activity_1");
    }

    private void createSocket(String url) throws URISyntaxException {
        final Socket socket = IO.socket(url);

        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                socket.send("hello");
            }
        });

//        socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
//            @Override
//            public void call(Object... args) {
//                System.out.println("连接关闭");
//            }
//        });

        socket.on(Socket.EVENT_MESSAGE, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                System.out.println(args[0]);
//                socket.disconnect();
            }
        });
        socket.connect();

        for (int i = 0; i < 200; i++) {
            RealTrack track = new RealTrack();
            track.setActivityId(Long.valueOf(new Random().nextInt(10)+1));
            track.setUserId(Long.valueOf(new Random().nextInt(10)+1));
            track.setLatitude(randomLonLat(0,180,0,90,"Lat"));
            track.setLongitude(randomLonLat(0,180,0,90,"Lon"));
            socket.send(JSON.toJSONString(track));
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
